import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

import { PermissionControlEntity } from '../permission-control/permission-control.entity';
import { RoleEntity } from '../role/role.entity';
import { CreatePermissionDto } from './dto/create-permission.dto';
import { UpdatePermissionDto } from './dto/update-permission.dto';
import { PermissionEntity } from './permission.entity';

@Injectable()
export class PermissionService {

  constructor(
    @InjectRepository(PermissionEntity)
    private readonly permissionRepo: Repository<PermissionEntity>,
    @InjectRepository(RoleEntity)
    private readonly roleEntity: Repository<RoleEntity>,
    @InjectRepository(PermissionControlEntity)
    private readonly permissionControlRepo: Repository<PermissionControlEntity>,
  ) {
  }

  async create(createPermissionDto: CreatePermissionDto) {
    // 拿到所有的 role
    const roles = await this.roleEntity
      .createQueryBuilder('role')
      .select('role.id')
      .where('role.deletedAt IS NULL')
      .getMany();

    const p = this.permissionRepo.create(createPermissionDto);
    const permission = await this.permissionRepo.save(p);

    for (const { id } of roles) {
      const pc = this.permissionControlRepo.create({
        permissionId: permission.id,
        roleId: id,
      });

      await this.permissionControlRepo.save(pc);
    }
  }

  async delete(id: number) {
    const p = await this.permissionRepo.findOneById(id);
    if (!p) {
      throw new NotFoundException('未找到该条数据');
    }
    this.permissionRepo.updateById(id, { deletedAt: new Date() });
  }

  update(id: number, updatePermissionDto: UpdatePermissionDto) {
    const p = this.permissionRepo.findOneById(id);
    if (!p) {
      throw new NotFoundException('未找到该条数据');
    }
    return this.permissionRepo.updateById(id, updatePermissionDto);
  }

  findAll(key: string = '') {
    return this.permissionRepo
      .createQueryBuilder('p')
      .where('p.key LIKE :key', { key: `%${key}%` })
      .andWhere('p.deletedAt IS NULL')
      .getMany();

    // todo 查 permissionControl 表
  }
}
